{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "from gs_quant.common import PayReceive, Currency\n",
    "from gs_quant.instrument import IRSwap\n",
    "from gs_quant.markets import PricingContext\n",
    "from gs_quant.markets.portfolio import Portfolio\n",
    "from gs_quant.risk import RollFwd, MarketDataPattern, MarketDataShock, MarketDataShockBasedScenario,MarketDataShockType\n",
    "from gs_quant.session import Environment, GsSession"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [],
   "source": [
    "# external users should substitute their client id and secret; please skip this step if using internal jupyterhub\n",
    "GsSession.use(Environment.PROD, client_id=None, client_secret=None, scopes=('run_analytics',))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [],
   "source": [
    "# define two swaps\n",
    "swap1 = IRSwap(termination_date='10y', notional_currency=Currency.USD, pay_or_receive=PayReceive.Pay, fixed_rate=0.007, name='10y')\n",
    "swap2 = IRSwap(termination_date='15y', notional_currency=Currency.USD, pay_or_receive=PayReceive.Pay, fixed_rate=0.007, name='15y')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [],
   "source": [
    "# create a couple of scenarios\n",
    "\n",
    "# 1bp Spot Shock\n",
    "ir_1bp_scenario = MarketDataShockBasedScenario(shocks={\n",
    "    MarketDataPattern('IR', 'USD') : MarketDataShock(shock_type=MarketDataShockType.Absolute, value=1e-4)})\n",
    "\n",
    "# 2bp Spot Shock\n",
    "ir_2bp_scenario = MarketDataShockBasedScenario(shocks={\n",
    "    MarketDataPattern('IR', 'USD') : MarketDataShock(shock_type=MarketDataShockType.Absolute, value=1e-4)})\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [],
   "source": [
    "# if we want to apply one scenario to many trades it is best to join those trades into a portfolio and send this in one calc\n",
    "\n",
    "portfolio = Portfolio([swap1, swap2], name='portfolio')\n",
    "\n",
    "# note you can append (and pop) trades into a portfolio but this is generally less efficient than just creating with list comprehension\n",
    "# also portfolios can themselves contain portfolios"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "H:\\code\\gs_quant\\gs_quant\\risk\\results.py:80: FutureWarning: The provided callable <built-in function sum> is currently using DataFrameGroupBy.sum. In a future version of pandas, the provided callable will be used directly. To keep current behavior pass the string \"sum\" instead.\n",
      "  pivot_df = df.pivot_table(values=values, index=index, columns=columns, aggfunc=aggfunc)\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th>risk_measure</th>\n",
       "      <th>Price</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>instrument_name</th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>10y</th>\n",
       "      <td>2.295177e+07</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>15y</th>\n",
       "      <td>3.253489e+07</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "risk_measure            Price\n",
       "instrument_name              \n",
       "10y              2.295177e+07\n",
       "15y              3.253489e+07"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# many trades with one scenario\n",
    "\n",
    "with ir_1bp_scenario:\n",
    "    prices = portfolio.price()\n",
    "\n",
    "prices.to_frame()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "22951766.87812186\n",
      "32534888.041928925\n"
     ]
    }
   ],
   "source": [
    "# now I want to apply 1 scenario to 1 trade and the other scenario to the 2nd trade\n",
    "# you could do this sequentially and that will work but be slow.  Better to nest the scenarios in a overarching context\n",
    "\n",
    "with PricingContext():  # this context just wraps the calcs so that they will be run in parallel\n",
    "    with ir_1bp_scenario:\n",
    "        p1 = swap1.price()\n",
    "    with ir_2bp_scenario:\n",
    "        p2 = swap2.price()\n",
    "\n",
    "print(p1.result())\n",
    "print(p2.result())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
